<template>
  <div>
    <div id="summernote"></div>
    <Modal  width="600px" title="文件上传" v-model="visibleUpload" :loading="true">
      <div class="operationBox">
        <div id="fileUpload" class="customerUpload">选择文件</div>
        <Button type="success" id="toServerBtn" :disabled="!ifFileQueue">开始上传</Button>
        <div class="upload__tip">最多10个文件，每个文件不超过10M</div>
      </div>
      <div class="fileShowBox">
        <ul class="uploadList" id="uploadList">
          <li v-show="!ifFileQueue" style="font-size: 14px; font-weight: 500;text-align: center">请上传文件</li>
        </ul>
      </div>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script type="text/ecmascript-6">
  import Vue from 'vue';
  import {SERVICE_URLS} from "../../libs/service.url";

  export default {
    components: {},
    props: {
      value: {
        default: '',
      },
      id:{
        type:String
      }
    },
    data() {
      return {
        _val : this.value,
        curEle:'',//当前Dom元素
        visibleUpload:false,
        fileList:[],
        uploader:'',//文件上传
        ifFileQueue:false, //是否存在队列
        summerNoteContext:'' //summerNote编辑器对象
      }
    },
    computed: {

    },
    created() {

    },
    mounted () {
      this.curEle=$('#summernote');
      let btn = this.template;
      $('#summernote').summernote({
        toolbar: [
          ['operate', ['undo','redo']],
          ['magic',['style']],
          ['style', ['bold', 'italic', 'underline', 'clear']],
          ['para', ['height','fontname','fontsize','ul', 'ol', 'paragraph']],
          ['color', ['color']],
          ['insert',['fileBtn','picture','video','link','table','hr']],
          ['layout',['fullscreen','codeview']]
        ],
        buttons: {
          fileBtn: btn
        },
        placeholder: '请输入内容',
        fontNames: ['宋体', '微软雅黑', '楷体', '黑体','隶书'],
        tabsize: 2,
        height:400,
        minHeight:300,
        maxHeight:null,
        focus: true,
        lang: 'zh-CN',
        callbacks : {
          onImageUpload: (files) => {
            this.uploadFile(files);
          },
          onChange: (e) => {
            this.emitVal(e);
          },
          onBlur : (e) => {
            this.$emit('onblur');
          }
        }
      });
      $('#summernote').summernote('fontName', '微软雅黑');
      $('#summernote').summernote('code', this.value);
      console.log('------------' + this.value)
    },
    watch: {
      value(val) {
        if (val != this.val) {
          this._val = val;
        }
      },
      visibleUpload:function(data){
        if(data){
          this.fileList=[];
          this.ifFileQueue=false;
        }
      }
    },
    methods: {
      uploadFile (files) {
        let formData = new FormData();
        let self = this;
        for(let i = 0,len = files.length; i < len; i++){
          formData.append("files", files[i]);
        }
        Vue.submit(self, {
          url: SERVICE_URLS.common.editorFileUpload,
          data: formData,
          callback: (_data) => {
            if (!_data || _data.length == 0) {
              return;
            }
            _data.forEach(d => {
              $('#summernote').summernote('insertImage',d.fileUrl);
            })
          }
        })
      },
      template(){
        let _this=this;
        var ui = $.summernote.ui;
        var button = ui.button({
          contents: '<i class="iconfont iconfujian1"></i>',
          tooltip: '附件上传',
          click: function () {
            _this.visibleUpload=true;
            setTimeout(function(){
              _this.initUploader();
            },0)
          }
        });
        return button.render();   // return button as jquery object
      },
      initUploader(){
        var _this=this;
        var $list=$('#uploadList');
        var state='pending';
        var $btn=$('#toServerBtn');
        var uploader = WebUploader.create({
          swf: 'https://cdn.bootcss.com/webuploader/0.1.1/Uploader.swf',
          server: SERVICE_URLS.common.fileUploads.path,
          pick: '#fileUpload',
          resize: false,
          fileVal : 'files',
          fileNumLimit: 10,
          fileSizeLimit: 10 * 1024 * 1024,
        });
        this.uploader=uploader;
        // 当有文件被添加进队列的时候
        uploader.on( 'fileQueued', function( file ) {
          $list.append( '<li id="' + file.id + '" class="fileItem">' +
            '<p class="uploadInfo ellipsis">' + file.name + '</p>' +
            '<div class="stateBox">' +
            '<p class="uploadState">等待上传</p>' +
            '<p class="cancelFile" attr="' + file.id + '" >取消上传</p>' +
            '</div>'+
            '<div class="progress">' +
            '<div class="progress-bar"></div>' +
            '</div>'+
            '</li>' );
          if(file){
            _this.ifFileQueue=true;
          }
        });
        $list.on('click','.stateBox .cancelFile',function(event){
          var target=event.target.getAttribute('attr');
          uploader.removeFile( target,true );
          $('#'+target).remove();
          var status=uploader.getStats();
          if(status.queueNum==0){
            _this.ifFileQueue=false
          }else{
            _this.ifFileQueue=true;
          }
        })
        uploader.on( 'uploadProgress', function( file, percentage ) {
          var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');
          // 避免重复创建
          if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
              '<div class="progress-bar" role="progressbar" style="width: 0%">' +
              '</div>' +
              '</div>').appendTo( $li ).find('.progress-bar');
          }
          $li.find('p.uploadState').text('上传中');
          $percent.css( 'width', percentage * 100 + '%' );
        });
        uploader.on( 'uploadSuccess', function( file,response ) {
          $( '#'+file.id ).find('p.uploadState').text('已上传');
          _this.$set( _this.fileList,_this.fileList.length,response.result[0])
        });
        uploader.on( 'uploadError', function( file ) {
          $( '#'+file.id ).find('p.uploadState').text('上传出错');
        });
        uploader.on( 'uploadComplete', function( file ) {
          $( '#'+file.id ).find('.progress').fadeOut();
        });
        uploader.on('uploadFinished',function(){
          var str=``;
          for (var i = 0; i < _this.fileList.length; i++) {
            var item = _this.fileList[i];
            str+=`<p><a href="${SERVICE_URLS.common.prefixUrl.path + item.fileUrl}" download="${item.fileName}">${item.fileName}</a></p>`;
          }
          var storageCode=_this.curEle.summernote('code');
          _this.curEle.summernote('reset');
          var node=$("<div>"+storageCode+str+"</div>")[0];
          _this.curEle.summernote('code',node);

          setTimeout(()=>{
            _this.visibleUpload=false;
          },1000)
        });
        uploader.on( 'all', function( type ) {
          if ( type === 'startUpload' ) {
            state = 'uploading';
          } else if ( type === 'stopUpload' ) {
            state = 'paused';
          } else if ( type === 'uploadFinished' ) {
            state = 'done';
          }
          if ( state === 'uploading' ) {
            $btn.text('暂停上传');
          } else {
            $btn.text('开始上传');
          }
        });
        $btn.on( 'click', function() {
          if ( state === 'uploading' ) {
            uploader.stop();
          } else {
            uploader.upload();
          }
        });
      },
      emitVal (e) {
        this._val = e;
        this.$emit('input', this._val);
      }
    }
  }
</script>

<style scoped lang="scss">
  .note-toolbar {
    text-align: left!important;
  }
  .fileShowBox{
    background-color: #f8f8f8;
    padding:5px 10px;
    border-radius: 3px;;
  }
  .operationBox .customerUpload{
    display: inline-block;
    /*padding:4px 15px;*/
    font-size: 14px;
    width:88px;
    height:32px;
    line-height: 32px;
    color:#fff;
    background-color: #0174fe;
    border: 1px solid #d8dce5;
    border-radius: 3px;
    font-weight: 500;
    cursor: pointer;
    position:relative;
    overflow: hidden;
    float:left;
  }
  .operationBox{
    width:200px;
    overflow: hidden;
    margin: 0 auto;
  }
  .operationBox #toServerBtn{
    float:left;
    margin-left:8px;
  }
  .uploadList{
    overflow: hidden;
    width:100%;
    .fileItem{
      width:100%;
      float:left;
      font-size:14px;
      font-weight: 500;
      border-bottom: 1px solid #dadada;
      &:hover .cancelFile{
        display: block;
      }
    }
  }
  .uploadInfo{
    width:80%;
    float:left;
    text-align: left;
  }
  .stateBox{
    width:20%;
    float:left;
    position: relative;

    .uploadState{
      width:100%;
      height:100%;
    }
    .cancelFile{
      cursor: pointer;
      color: #fff;
      width:100%;
      height:100%;
      display: none;
      position:absolute;
      top:0;
      left:0;
      background-color: #00b7ee;
    }
  }
  .uploadList .progress{
    width:100%;
    height:4px;
    margin-bottom: 4px;
    float:left;
  }
  .uploadList .progress-bar{
    line-height: 4px;
    height:4px;
    overflow: hidden;
  }


</style>
